/*
 * @Author: yangzonglong
 * @Date: 2021-03-04 15:04:22
 * @version: v1.0.0
 * @Descripttion: 
 * @LastEditors: yangzonglong
 * @LastEditTime: 2023-03-22 20:30:19
 * @Auditor: 
 */
import React, { useMemo, useRef } from 'react';
import { Form, InputNumber, Tooltip } from 'antd';
import { FormItemProps } from '../components/InputFormItemController';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { InputNumberProps as AntdInputNumberProps } from 'antd/lib/input-number';
import { CanvasItemProps } from './../../interface';
import { regExpPatterns } from '../../config';
import { QuestionCircleOutlined } from '@ant-design/icons';
import styles from './style.module.scss';

interface FixAntdInputNumberProps extends AntdInputNumberProps {
  formatterMoney?: boolean;
  hideArrow?: boolean;
  bindName?: string;
  showFiled?: string;
  placeholderEn?: string;
  suffix?: string;
  prefix?: string;
}

export interface InputNumberProps extends CanvasItemProps {
  inputProps?: FixAntdInputNumberProps;
  formItemProps?: FormItemProps;
  disabled?: boolean;
}

const preStyle = { padding: 0, margin: 0 };

const parser = (value: string | undefined) => {
  if (value) return value.replace(/\$\s?|(,*)/g, '');
  return '';
};

const App = (props: InputNumberProps, ref: React.Ref<HTMLDivElement | null>) => {
  const tempFormat = useRef('');
  const { disabled, inputProps, formItemProps, domComplete, ...canvasProps } = props;

  useQueryControlWrap(canvasProps.id, formItemProps?.name, domComplete);

  const rules = useMemo(() => {
    let _rules = formItemProps?.rules ? [...formItemProps?.rules] : [{ required: false }];
    return formItemProps?.checkRule ? [..._rules, regExpPatterns[formItemProps?.checkRule]] : _rules;
  }, [formItemProps]);

  const _disabled = useMemo(() => {
    if (typeof disabled === 'boolean') return disabled;
    return formItemProps?.disabled || !!inputProps?.bindName;
  }, [disabled, formItemProps, inputProps]);

  const formatter = (value: any) => {
    if (tempFormat.current) {
      const temp = tempFormat.current;
      tempFormat.current = '';
      return temp;
    }

    const arr = (value + '').split('.');
    let integer = arr[0] || '';

    if (integer.length > 3) {
      let str = '', len = integer.length;

      for (let i = len - 1; i >= 0; i--) {
        if ((len - i) % 3 === 0 && i !== 0) {
          str = ',' + integer[i] + str;
        } else {
          str = integer[i] + str;
        }
      }

      if (_disabled) {
        if (arr[1]?.length === 1) {
          return str + '.' + arr[1] + 0;
        }

        if (arr[1]?.length > 2) {
          return str + '.' + arr[1].substring(0, 2);
        }

        return str + '.' + (arr[1] || '00');
      }

      if (!(value + '').includes('.')) return str;
      return str + '.' + (arr[1] || '');
    } else {
      if (_disabled) {
        if (isNaN(value.replace(/,/g, ''))) {
          value = '0.00';
        } else {
          if (arr[1]) {
            if (arr[1].length >= 2) {
              value = `${arr[0]}.${arr[1].substring(0, 2)}`;
            } else {
              value = `${arr[0]}.${arr[1]}0`;
            }
          } else if (arr[0]) {
            value = `${arr[0]}.00`;
          }
        }
      }

      return value;
    }
  };

  function onBlur(e: React.BaseSyntheticEvent) {
    const value = (e.target.value || '');
    const arr = value.split('.');

    if (isNaN(value.replace(/,/g, ''))) {
      tempFormat.current = '0.00';
    } else {
      if (arr[1]) {
        if (arr[1].length >= 2) {
          tempFormat.current = `${arr[0]}.${arr[1].substring(0, 2)}`;
        } else {
          tempFormat.current = `${arr[0]}.${arr[1]}0`;
        }
      } else if (arr[0]) {
        tempFormat.current = `${arr[0]}.00`;
      }
    }
  }

  const label = localStorage.i18nextLng === 'en' ? formItemProps?.labelEn : formItemProps?.label;
  const placeholder = localStorage.i18nextLng === 'en' ? inputProps?.placeholderEn : inputProps?.placeholder;
  const tooltip = localStorage.i18nextLng === 'en' ? formItemProps?.tooltipEn : formItemProps?.tooltip;
  const overlayInnerStyle = formItemProps?.tooltipWidth ? { width: formItemProps?.tooltipWidth } : {};

  return (
    <Form.Item
      {...canvasProps}
      {...formItemProps}
      rules={rules}
      tooltip={undefined}
      label={formItemProps?.showTooltip && tooltip ? <Tooltip overlayInnerStyle={overlayInnerStyle} title={<pre style={preStyle}>{tooltip}</pre>}>
        <span>{label}<QuestionCircleOutlined style={{ color: '#999', marginLeft: 4 }} /></span>
      </Tooltip> : label}
    >
      <InputNumber
        style={{ width: '100%' }}
        className={styles['money_' + (formItemProps?.style?.textAlign || 'left')]}
        {...(inputProps as InputNumberProps)}
        placeholder={_disabled ? '' : placeholder}
        {...(inputProps?.formatterMoney ? {
          parser,
          formatter,
          onBlur,
          step: 0.01,
          precision: 2
        } : {
          precision: typeof inputProps?.precision === 'number' ? inputProps?.precision : undefined
        })}
        controls={inputProps?.hideArrow ? false : true}
        disabled={_disabled} />
    </Form.Item>
  );
};

export default App;